import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue')
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/Layout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { title: '系统首页' }
      },
      {
        path: '/products',
        name: 'Products',
        component: () => import('@/views/product/Products.vue'),
        meta: { title: '商品管理' }
      },
      {
        path: '/products/add',
        name: 'AddProduct',
        component: () => import('@/views/product/AddProduct.vue'),
        meta: { title: '添加商品' }
      },
      {
        path: '/products/edit/:id',
        name: 'EditProduct',
        component: () => import('@/views/product/EditProduct.vue'),
        meta: { title: '编辑商品' }
      },
      {
        path: '/orders',
        name: 'Orders',
        component: () => import('@/views/order/Orders.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: '/orders/:id',
        name: 'OrderDetail',
        component: () => import('@/views/order/OrderDetail.vue'),
        meta: { title: '订单详情' }
      },
      {
        path: '/finance',
        name: 'Finance',
        component: () => import('@/views/finance/Finance.vue'),
        meta: { title: '财务管理' }
      },
      {
        path: '/analytics',
        name: 'Analytics',
        component: () => import('@/views/analytics/Analytics.vue'),
        meta: { title: '数据分析' }
      },
      {
        path: '/settings',
        name: 'Settings',
        component: () => import('@/views/settings/Settings.vue'),
        meta: { title: '系统设置' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    if (userStore.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
